<script setup lang="ts">
import {computed, onMounted, reactive, ref} from 'vue'
import PanelBox from "@/components/ProjectPanel/panel.vue";
import {CircleCloseFilled} from "@element-plus/icons-vue";
import {addUser, getAllUser,deleteUserById,updateUser} from "@/api/user/user";
import {ElMessage, ElMessageBox, FormInstance, FormRules} from "element-plus";
import {createHashWithFixedSalt} from "@/utils/HashFixedSalt.ts";

const getTableData = (pageDate:any)=>{
  getAllUser(pageDate).then(res=>{
    tableData.value = res.data.data.content
    page.total = res.data.data.totalElements
  })
}

onMounted(()=>{
  const pageData = {
    page: page.num,
    size: page.size,
  }
  getTableData(pageData)
})

interface User {
  account: string
  name: string
  tel:string
  roleName: string
}

interface AddUserData {
  account: string
  name: string
  tel: string
  ps: string
  roleName: string
}

const search = ref('')
const addVisible = ref(false)
const editVisible = ref(false)
const tableData = ref([])

const addRuleFormRef = ref<FormInstance>()
const editRuleFormRef = ref<FormInstance>()

const page =reactive({
  num:0,
  size:10,
  total:0
})

let addUserData = reactive<AddUserData>({
  account:'',
  name:'',
  tel:'',
  ps:'',
  roleName:''
})
let editUserData = reactive({
  account:'',
  name:'',
  tel:'',
  roleName:''
})

const addUserRules = reactive<FormRules<AddUserData>>({
  account: [
    {required: true, message: '请输入账号', trigger: 'blur'},
    {min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur'}
  ],
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
    {min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur'}
  ],
  tel: [
    {required: true, message: '请输入电话', trigger: 'blur'},
    {min: 11, max: 11, message: '长度为11位', trigger: 'blur'}
  ],
  ps: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'}
  ],
  roleName: [
    {required: true, message: '请选择角色', trigger: 'blur'}
  ]
})


const filterTableData = computed(() =>
    tableData.value.filter(
        (data) =>
            !search.value ||
            data.name.toLowerCase().includes(search.value.toLowerCase())
    )
)
const handleEdit = (row: User) => {
  editVisible.value = true
  editUserData = row
}
const handleDelete = (index: number, row: User) => {
  ElMessageBox.confirm(`确定删除第${index+1}行，姓名为${row.name}的用户, 是否继续?`, '此操作将删除该用户下所有对应的文件信息', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(()=>{
    deleteUserById(row.id).then(res=>{
      if (res.data.code === 200) {
        const pageData = {
          page: page.num,
          size: page.size,
        }
        getTableData(pageData)
        ElMessage.success('删除成功')
      }else{
        ElMessage.error(res.data.msg)
      }
    })
  })
}

const handleAdd = () => {
  addVisible.value = true
}

const handleAddUser = async (formEl: FormInstance | undefined)=>{
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        let data = addUserData
        data.ps = createHashWithFixedSalt(data.ps).hashedPassword
          addUser(data).then(res=>{
            if (res.data.code === 200) {
              addVisible.value = false
              const pageData = {
                page: page.num,
                size: page.size,
              }
              addUserData.account = '',
              addUserData.name = '',
              addUserData.tel = '',
              addUserData.ps = '',
              addUserData.roleName=''
              getTableData(pageData)
              ElMessage.success('添加成功')
            }else{
              ElMessage.error(res.data.msg)
            }
          })
      }
    })
}

const handleEditUser = async (formEl: FormInstance | undefined)=>{
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid){
      updateUser(editUserData).then(res=>{
        if (res.data.code === 200){
          editVisible.value = false
          const pageData = {
            page: page.num,
            size: page.size,
          }
          getTableData(pageData)
          ElMessage.success('修改成功')
        }else{
          ElMessage.error(res.data.msg)
        }
      })
    }
  })
}

const handlePagination = (val:number) => {
  page.num = val
  const pageData = {
    page: val-1,
    size: page.size,
  }
  getTableData(pageData)
}

</script>

<template>
  <div class="context">
    <panel-box :has-body="true" :has-body-title="true" :has-driver="true" :has-foot="true">
      <template #body-title>
        <span>用户管理</span>
      </template>
      <template #body-button>
        <el-button class="context-add-btn" @click="handleAdd">新增用户</el-button>
      </template>
      <template #body-table>
        <el-table stripe :data="filterTableData" max-height="800px" style="width: 100%;" size="large" empty-text="暂无数据">
          <el-table-column label="账号(登录用户名)" prop="account" />
          <el-table-column label="姓名" prop="name" />
          <el-table-column label="手机号" prop="tel" />
          <el-table-column label="账户类型" prop="roleName" >
            <template #default="scope">
              <el-tag effect="dark" v-if="scope.row.roleName === '管理员'">管理员</el-tag>
              <el-tag effect="dark" v-else-if="scope.row.roleName === '用户'" type="info">用户</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="right">
            <template #header>
              <el-input v-model="search" size="small" placeholder="输入要搜索的姓名" />
            </template>
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)"
              >修改</el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>

        </el-table>

      </template>
      <template #body-table-action-pagination>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="page.total"
            @change="handlePagination"
        />
      </template>
    </panel-box>
    <el-dialog v-model="addVisible" :show-close="false" >
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <span :id="titleId" :class="titleClass">新增用户</span>
          <el-button type="danger" @click="close">
            <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
            关闭
          </el-button>
        </div>
      </template>
      <el-form
          ref="addRuleFormRef"
          :rules="addUserRules"
          :model="addUserData">
        <el-form-item label="用户名" label-width="100px" prop="account">
          <el-input v-model="addUserData.account" />
        </el-form-item>
        <el-form-item label="姓名" label-width="100px" prop="name">
          <el-input v-model="addUserData.name" />
        </el-form-item>
        <el-form-item label="手机号" label-width="100px" prop="tel">
          <el-input v-model="addUserData.tel" />
        </el-form-item>
        <el-form-item label="密码" label-width="100px" prop="ps">
          <el-input show-password v-model="addUserData.ps" />
        </el-form-item>
        <el-form-item label="账户类型" label-width="100px" prop="roleName">
          <el-select v-model="addUserData.roleName" placeholder="请选择账户类型">
            <el-option label="管理员" value="管理员" />
            <el-option label="用户" value="用户" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddUser(addRuleFormRef)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="editVisible" :show-close="false" >
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <span :id="titleId" :class="titleClass">修改用户信息</span>
          <el-button type="danger" @click="close">
            <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
            关闭
          </el-button>
        </div>
      </template>
      <el-form
          ref="editRuleFormRef"
          :rules="addUserRules"
          :model="editUserData">
        <el-form-item label="用户名" label-width="100px" prop="account">
          <el-input v-model="editUserData.account" />
        </el-form-item>
        <el-form-item label="姓名" label-width="100px" prop="name">
          <el-input v-model="editUserData.name" />
        </el-form-item>
        <el-form-item label="手机号" label-width="100px" prop="tel">
          <el-input v-model="editUserData.tel" />
        </el-form-item>
        <el-form-item label="账户类型" label-width="100px" prop="roleName">
          <el-select v-model="editUserData.roleName" placeholder="请选择账户类型">
            <el-option label="管理员" value="管理员" />
            <el-option label="用户" value="用户" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditUser(editRuleFormRef)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.context{
  width: calc(100% - 20px);

  .my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    gap: 16px;
  }

  &-add-btn{
    height: 30px;
    width: 70px;
    color: #ffffff;
    background: linear-gradient(to right, #79bbff, #ff7a7a);
    margin-right: 20px;
  }

  &-add-btn:hover{
    background: linear-gradient(to right, #ff7a7a, #79bbff);
  }

  &-table{
    width: calc(100% - 20px);
    margin:10px auto;
    height: 100%;
  }
}
</style>
